//
//  HomePageLayout.m
//  product_B
//
//  Created by lanou on 16/5/30.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "HomePageLayout.h"

@interface HomePageLayout ()
@property (nonatomic,strong)NSMutableArray *columsHeights;
@property (nonatomic,strong)NSMutableArray *atts;

@end
@implementation HomePageLayout

- (NSMutableArray *)columsHeights{
    if (!_columsHeights) {
        _columsHeights = [NSMutableArray array];
    }
    return _columsHeights;
}

- (NSMutableArray *)atts{
    if (_atts == nil) {
        _atts = [NSMutableArray array];
    }
    return _atts;
}

- (void)prepareLayout{
    [super prepareLayout];
    for (int i = 0; i <= self.numberOfColum; i++) {
        self.columsHeights[i] = @(self.sectionInset.top);
    }
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    for (int i = 0; i < count; i++) {
        NSInteger lowest = [self getLowestColum];
        CGFloat x = self.sectionInset.left + (self.width + self.space) * lowest;
        CGFloat y = [self.columsHeights[lowest] floatValue] + self.space;
        
        CGFloat width = self.width;
        CGFloat height = self.resultBlock(i);
        
        // 将布局信息（frame）保存到布局对象中
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        UICollectionViewLayoutAttributes *att = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        
        att.frame = CGRectMake(x, y, width, height);
        
        [self.atts addObject:att];
        
        // 3.更新最矮列的高度
        self.columsHeights[lowest] = @(y + height);

    }
}

- (NSInteger)getLowestColum{
    int lowest = 0;
    float height = MAXFLOAT;
    for (int i = 0; i < self.numberOfColum; i++) {
        if (height > [self.columsHeights[i] floatValue]) {
            height = [self.columsHeights[i] floatValue];
            lowest = i;
        }
    }
    return lowest;
}

// 返回布局属性数组
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return self.atts;
}

// 确定滚动范围
- (CGSize)collectionViewContentSize
{
    CGFloat height = [self getHeightestColum];
    return CGSizeMake(0, height);
}

// 获取最高列高度
- (CGFloat)getHeightestColum{
    CGFloat heightest = 0;
    for (int i = 0; i < self.numberOfColum; i++) {
        if (heightest < [self.columsHeights[i] floatValue]) {
            heightest = [self.columsHeights[i] floatValue];
        }
    }
    return heightest;
}
@end
